﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Util;
using LM.YF.K3Cloud.Plugin.Models;
using LM.YF.K3Cloud.Plugin.Models.Grasses;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 鹿奔 240418
    /// </summary>
    [Description("销售出库单表单插件（如果是过账发货，则不允许保存）"), HotUpdate]
    public class SaleOutstockOrderBillPlugin : AbstractBillPlugIn
    {
        #region MyRegion

        /// <summary>
        /// 单据体
        /// </summary>
        ElementKeySchema FEntity = new ElementKeySchema
        {
            FormKey = "FEntity",
            DbKey = "T_SAL_OUTSTOCKENTRY",
            OrmKey = "SAL_OUTSTOCKENTRY"
        };

        /// <summary>
        /// 单据体-仓库
        /// </summary>
        ElementKeySchema FStockID = new ElementKeySchema
        {
            FormKey = "FStockID",
            DbKey = "FSTOCKID",
            OrmKey = "StockID"
        };

        /// <summary>
        /// 单据体-实发数量
        /// </summary>
        ElementKeySchema FRealQty = new ElementKeySchema
        {
            FormKey = "FRealQty",
            DbKey = "FREALQTY",
            OrmKey = "RealQty"
        };

        #endregion

        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);

            #region 如果是过账发货，则锁定数量、仓库字段

            var billId = Convert.ToInt32(View.Model.GetPKValue());
            var hyId = GetHuoYunDanIdList(billId);
            if (!(hyId?.Count() > 0))
            {
                return;
            }

            // 存在货运单，说明是过账发货生成的出库单
            // 锁定数量、仓库
            var entity = View.BusinessInfo.GetEntity(FEntity.FormKey);
            var entityObjects = View.Model.GetEntityDataObject(entity);
            foreach (var entityObject in entityObjects)
            {
                View.StyleManager.SetEnabled(FRealQty.FormKey, entityObject, null, false);
                View.StyleManager.SetEnabled(FStockID.FormKey, entityObject, null, false);
            }

            #endregion
        }

        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);

            #region 如果该出库单间接关联的货运单下游存在应付单，则不允许保存

            var billId = Convert.ToInt32(View.Model.GetPKValue());
            var hyIdList = GetHuoYunDanIdList(billId);
            if (!(hyIdList?.Count() > 0))
            {
                return;
            }

            var hyIds = hyIdList.Select(item => item.EntryId);
            var hyIdString = string.Join(",", hyIds);

            var sql = $@"select distinct c.FBILLNO as '应付单编号', e.FBILLNO as '货运单编号'
                from T_AP_PAYABLE_LK as a-- 应付单
                inner join T_AP_PAYABLEENTRY as b on b.FENTRYID = a.FENTRYID
                inner join T_AP_PAYABLE as c on c.FID = b.FID
                inner join RDLV_t_DiliveOrdEntry as d on d.FEntryID = a.FSID
                inner join RDLV_t_DiliveOrder as e on e.FID = d.FID
                where 1 = 1
                and a.FRULEID in ('5a27b083-1a40-405b-85ab-6e0206952a14', '5db4c921-1912-4c7a-bf36-b2513f5f5bee', '97952d76-d612-9c12-11ee-b4fd4363ba0b')
                and a.FSID in ({hyIdString});";

            var yfIds = DBUtils.ExecuteDynamicObject(Context, sql);
            if (!(yfIds?.Count > 0))
            {
                return;
            }
            // 存在应付单

            var message = string.Join("\r\n", yfIds.Select(item => $"该销售出库单间接关联的货运单【{item["货运单编号"]}】下游存在应付单【{item["应付单编号"]}】，因此该出库单不允许修改！"));
            View.ShowWarnningMessage(message);
            e.Cancel = true;

            #endregion
        }

        /// <summary>
        /// 获取与该出库单间接关联的货运单的ID
        /// </summary>
        private IEnumerable<vahnwab> GetHuoYunDanIdList(int billId)
        {
            var sql = $@"select d.FID, d.FEntryID
                from T_SAL_OUTSTOCKENTRY_LK as a-- 销售出库单单据转换表
                inner join T_SAL_OUTSTOCKENTRY as b on b.FENTRYID = a.FENTRYID-- 销售出库单分录表，根据销售出库单ID获取其分录的上游发货通知单分录ID
                inner join RDLV_t_DiliveOrdEntry_LK as c on c.FRuleId in ('451ff7a3-2b1c-4e07-a611-e42152e94eff', 'dd837750-dc5d-44ca-8e02-1c03b8b825ed') and c.FSId = a.FSID-- 货运单分录表，根据发货通知单分录ID获取其下游货运单分录ID
                inner join RDLV_t_DiliveOrdEntry as d on d.FEntryID = c.FEntryID 
                where a.FRULEID = 'DeliveryNotice-OutStock'
                and b.FID = {billId};";
            var hyDataCollection = DBUtils.ExecuteDynamicObject(Context, sql);
            var idList = hyDataCollection?.Select(item => new vahnwab
            {
                EntryId = Convert.ToInt32(item["FEntryID"]),
                Id = Convert.ToInt32(item["FID"]),
            });
            return idList;
        }
    }
}
